var showZan = '3';
var comment_tips = '说点什么吧';
var show_floor = '1';
var showQQ = '1';
var comment_ipaddr = '';
var PLUS_URL = "/plus";
var visitor_fill = "QQ号";
var is_login = 0;
var comment_at = "1";
var datas={};
var comment_basecolor = "#007bf5";
var comment_uppic = "off";
// js动态加载表情
if (showZan=='') showZan=3;
if (comment_tips=='') comment_tips='说点什么吧';
if (show_floor=='') show_floor='1';
if (showQQ=='') showQQ='1';
if (comment_uppic=='') comment_uppic='off';
if (showQQ=='2'){
    $(".ds-add-emote").hide();
}
if (comment_uppic=='off'){
    $("#qyUploadBtn").hide();
}

if (comment_ipaddr=='') comment_ipaddr='1';
tuzkiNumber = 1;
emoji2html('.divcomment');

$(function() {


    var show_num = [];
    draw(show_num);
    $("#canvas").on('click', function() {
        draw(show_num);
    })
    $(".sendpl").on('click', function() {
        var val = $(".input-val").val().toLowerCase();
        var num = show_num.join("");
        if (val == '') {
            layer.msg('请输入验证码', function() {});
        } else if (val == num) {
            comment(this)
            $(".input-val").val('');
            draw(show_num);

        } else {
            layer.msg('验证码错误，请重新输入', function() {});
            $(".input-val").val('');
            draw(show_num);
        }
    })
})

// 验证码
function draw(show_num) {
    var canvas_width = $('#canvas').width();
    var canvas_height = $('#canvas').height();
    var canvas = document.getElementById("canvas"); //获取到canvas的对象，演员
    var context = canvas.getContext("2d"); //获取到canvas画图的环境，演员表演的舞台
    canvas.width = canvas_width;
    canvas.height = canvas_height;
    var sCode = "A,B,C,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,W,X,Y,Z,1,2,3,4,5,6,7,8,9,0";
    var aCode = sCode.split(",");
    var aLength = aCode.length; //获取到数组的长度

    for (var i = 0; i <= 3; i++) {
        var j = Math.floor(Math.random() * aLength); //获取到随机的索引值
        var deg = Math.random() * 30 * Math.PI / 180; //产生0~30之间的随机弧度
        var txt = aCode[j]; //得到随机的一个内容
        show_num[i] = txt.toLowerCase();
        var x = 10 + i * 20; //文字在canvas上的x坐标
        var y = 20 + Math.random() * 8; //文字在canvas上的y坐标
        context.font = "bold 23px 微软雅黑";
        context.translate(x, y);
        context.rotate(deg);
        context.fillStyle = randomColor();
        context.fillText(txt, 0, 0);
        context.rotate(-deg);
        context.translate(-x, -y);
    }
    for (var i = 0; i <= 5; i++) { //验证码上显示线条
        context.strokeStyle = randomColor();
        context.beginPath();
        context.moveTo(Math.random() * canvas_width, Math.random() * canvas_height);
        context.lineTo(Math.random() * canvas_width, Math.random() * canvas_height);
        context.stroke();
    }
    for (var i = 0; i <= 30; i++) { //验证码上显示小点
        context.strokeStyle = randomColor();
        context.beginPath();
        var x = Math.random() * canvas_width;
        var y = Math.random() * canvas_height;
        context.moveTo(x, y);
        context.lineTo(x + 1, y + 1);
        context.stroke();
    }
}

function randomColor() { //得到随机的颜色值
    var r = Math.floor(Math.random() * 256);
    var g = Math.floor(Math.random() * 256);
    var b = Math.floor(Math.random() * 256);
    return "rgb(" + r + "," + g + "," + b + ")";
}


$('body').on('click', '[data-zan]', function () {
    var id = $(this).data("id");
    var changeId=$(this).attr('data-zan');
    var old=$('#'+changeId).text();
    var subject = $(this).data("subject");
    $.ajax({
        cache: true,
        type: "POST",
        url: config.api.user_praise+"?subject="+subject+"&id=" + id,
        success: function(res) {
            if(res.code==1){
                $('#'+changeId).html(Math.ceil(old+1));
            }
            layer.msg(res.msg);
        }
    })
})

$("a.collect").click(function() {
    var aid = $(this).data("id");
    $.ajax({
        cache: true,
        type: "POST",
        url: config.api.user_favorite+"?aid=" + aid,
        success: function(res) {
            layer.msg(res.msg);
        }
    })
})


/**
 * 格式化数字为一个定长的字符串，前面补0
 * @param  int Source 待格式化的字符串
 * @param  int Length 需要得到的字符串的长度
 * @return int        处理后得到的数据
 */
function formatNum(Source, Length) {
    var strTemp = "";
    for (i = 1; i <= Length - Source.toString().length; i++) {
        strTemp += "0";
    }
    return strTemp + Source;
}
function emoji2html(o){
    $(o).emojiParse({
        basePath: config.api.emoji_dir,
        icons: emojiLists,
        // animation: 'none',
    });
}

/**
 * 在textarea光标后插入内容
 * @param  string  str 需要插入的内容
 */
function insertHtmlAtCaret(str) {
    var sel, range;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.deleteContents();
            var el = document.createElement("div");
            el.innerHTML = str;
            var frag = document.createDocumentFragment(), node, lastNode;
            while ((node = el.firstChild)) {
                lastNode = frag.appendChild(node);
            }
            range.insertNode(frag);
            if (lastNode) {
                range = range.cloneRange();
                range.setStartAfter(lastNode);
                range.collapse(true);
                sel.removeAllRanges();
                sel.addRange(range);
            }
        }
    } else if (document.selection && document.selection.type != "Control") {
        document.selection.createRange().pasteHTML(str);
    }
}
var temp = $("#pl-template"),
    aid = temp.data("id");
/*获取数据，并且初始化*/
request({
    url: config.api.comment_data,
    data:{aid:aid},
    loading: false,
    success: function (res) {

        datas = res;
        var data=res.data;

        var comments = comments_data(data);
        var comments_hot = comments_data(data, 1);

        $(".bq-hfcount font").html(castnum(parseInt(data.pl) + parseInt(data.hf)) + "次");

        var numof = $(".data .number span");
        numof.eq(0).html(castnum(data.tgcount));
        numof.eq(1).html(castnum(data.tgsuccess));
        numof.eq(2).html(castnum(data.allgood)).attr("data-dz", data.allgood);
        var athour = $(".athuor-info .btn a");
        data.qq && athour.eq(0).attr("href", "javaScript:lxzz('" + data.qq + "');");

        if (data.pl) {
            $(".plnumber").html(castnum(data.pl) + "条评论，" + castnum(data.hf) + "条回复");
        }


        if (data.allow==0) {

            $(".sendpl").addClass("disabled");
            $('.qy-comment-box').hide();
        }


        var user = isLogin('info');
        if (user.status) {

            $(".my-nick").html("<img src='" + user['avatar'] + "' />" + user.nick);
            $(".logineds").show();
            // if (data.allow==0) {
            //
            //     // layedit_iframe.after('<div style="position: absolute; width: 100%; height: calc(100% - 43px ); left: 0; bottom: 0; background: #f9f9f9;"><div class="everyone"> 该文章已被管理员关闭评论 </div></div>');
            // }
        } else {
            // if (data.allow) {
            //     layedit_iframe.after('<div style="position: absolute; width: 100%; height: calc(100% - 43px ); left: 0; bottom: 0; background: #f9f9f9;"><div class="everyone"> 该文章已被管理员关闭评论 </div></div>');
            // } else {
            //     layedit_iframe.after('<div class="closepl"><div class="everyone"> 请先<a href="javaScript:openLoginK()">登录</a>后再评论 </div></div>');
            // }
        }
        /*评论的写入*/
        var temp_html = $("#pl-template").html();

        if (comments_hot && comments_hot.length > 0) {
            // laytpl(temp_html).render(comments_hot, function (html) {
            //     $("#hot-pl").append(html);
            // });
            //
            renderTemplate(comments_hot,'pl-template', 'hot-pl',null,null);
            $("#hot-pl").addClass("hvs").show();
        } else {
            $("#new-pl").addClass("hvs");
        }

        if (comments && comments.length > 0) {
            $("#new-pl").show();


            renderTemplate(comments,'pl-template', '#new-pl',null,'append',null);

            emoji2html("#new-pl");
            $("#ulcommentlist").hide();
            if (data.pages > 1) {
                $(".showMore").css("display", "block").data("page", 1);
            }
        }

    }
});

/*发送评论*/
var ifs = true;
function comment(obj){
    var that = $(obj);
    if (!that.hasClass("disabled")) {
// console.log(that.parents('.b-box-textarea-body').html());
        var content = that.parents('.b-box-textarea-body').find('.b-box-content').val();

        if (content) {
            that.html('<i class="layui-icon layui-icon-loading layui-icon layui-anim layui-anim-rotate layui-anim-loop"></i>');
            ifs = false;
            var data = {
                content: content,
                aid: aid,
                pid: that.attr('pid')
            };
            request({
                url: config.api.comment,
                data: data,
                loading: false,
                done: function (result) {

                    if (result.code === 1) {
                        var new_data=result.data;
                        var comment_id = data.id;
                        setTimeout(function () {
                            ifs = true;
                            // $(document.getElementById('LAY_layedit_1').contentWindow.document.body).html("");
                            $('.b-box-content').val("");
                            var newData={};
                            Object.assign(newData,new_data,{
                                "up": 0,
                                "reply_count": 0,
                                "reply": []
                            });

                            console.log(newData);
                            renderTemplate([newData],"pl-template", '#new-pl .title',null,1);

                            emoji2html(".li-content:eq(0)");


                            // emoji2html("#new-pl");
                            $("#ulcommentlist").hide();
                            if (result.data.pages > 1) {
                                $(".showMore").css("display", "block").data("page", 1);
                            }

                        }, 1000);
                    } else {
                        that.attr('disabled', true).html("评论");
                    }

                    //layer.msg(result.msg);
                }
            });

        } else {
            layer.msg("请先输入评论内容..");
        }
    }
}

/* 子评论加载更多 */
$("body").delegate(".zi-loadmore", "click", function (e) {
    var that = $(this);
    that.parent().find("ul li").each(function (i, e) {
        e.removeAttribute('hidden');
    });
    that.hide();
});

/* 父评论加载更多 */
$("body").delegate(".showMore", "click", function (e) {
    var that = $(this);
    that.html("正在加载中...");
    var temp = $("#pl-template");
    var page = parseInt(that.data("page")), pages = datas.data.pages;
    if (page < pages) {
        request({
            url: config.api.comment_data,
            data: {page: page + 1},
            success: function (result) {
                that.data('page', ++page);
                laytpl(temp.html()).render(comments_data(result.data), function (html) {
                    $("#new-pl").append(html);
                    that.html("查看更多评论 ");
                    (page >= pages) && that.html("没有更多了");
                });
            }
        });

    } else {
        that.html("没有更多了");
    }
    // console.log(that.data('page'), pages);
});
$("body").delegate(".ds-toolbar-button", "click", function (e) {
    $("textarea.wdl").emoji({button:".ds-toolbar-button.cr",showTab:true,animation:"fade",basePath:config.api.emoji_dir,icons:emojiLists,});

});
/* 点击回复按钮 */
var atext = "";
$("body").delegate(".huifubtn", "click", function (e) {

    if (datas.data.allow==0) {
        layer.msg("管理员已禁止评论");
    } else {
        // if (isLogin()) {
        if ($(this).html() === "收起") {
            $(this).html(atext);
            $(".huifu").remove();
        } else {
            if ($(".huifu").length > 0) {
                $(".huifu").parent().find(".huifubtn").html(atext);
            }
            atext = $(this).html();
            $(this).html("收起");
            $(".huifu").remove();

            // var aid = $(obj).attr('aid');
            var pid = $(this).parent().attr('data-id');

            // var username = $(obj).attr('username');
            // var floor = $(obj).parents('.reply').find(".gh").length;
            // if(!comment_basecolor) comment_basecolor = '#39a7e4';
            // floor = parseInt(floor)+1;
            var emoteHtml='<a class="ds-toolbar-button layui-icon layui-icon-face-smile-fine hf" title="插入表情" >&nbsp;</a>';


            var emojiopne = '<script>$("textarea.hf").emoji({button:".ds-toolbar-button.hf",showTab:true,animation:"fade",basePath:config.api.emoji_dir,icons:emojiLists,});</script>';
            var str = '<div class="b-box-textarea"><div class="b-box-textarea-body"><textarea class="b-box-content hf" contenteditable="true" onfocus="delete_hint(this)"></textarea><ul class="b-emote-submit"><li class="b-emote">'+emoteHtml+'<div class="b-tuzki"></div></li><li class="b-submit-button"><input type="button" value="评 论" aid="' + aid + '" pid="' + pid + '" onclick="comment(this)"  style="background-color: '+comment_basecolor+';"></li><li class="b-clear-float"></li></ul></div><div class="error-tip"></div></div>'+emojiopne+'';

            // var parentObj = $(this).parents('.zhiChi').eq(0).append(str);

            $(this).parent().append(str);

            // $(this).parent().append('<div class="huifu clearfix"> <input class="huifucontent"/> <b class="sendhf">回复</b> </div>');


            $(".huifucontent").focus();
        }
        // } else {
        //     layer.msg("没有登录");
        //     // location="/user/login.html";
        // }
    }
});
/*开始回复按钮*/
var sendhf = true;
$("body").delegate(".sendhf", "click", function (e) {
    var that = $(this);
    var content = that.parent().find(".huifucontent").val();
    var comment_id = that.parents('.li-info').data("id");
    var pid = that.attr("pid");

    var user = isLogin(true);
    if (content && sendhf) {
        content = content.trim();
        sendhf = false;
        that.html('<i class="layui-icon layui-icon-loading layui-icon layui-anim layui-anim-rotate layui-anim-loop"></i>');
        request({
            url: config.api.comment,
            data: {content: content, aid: aid, pid: pid, comment_id: comment_id},
            done: function (result) {

                if (result.code === 1) {

                    var comm_id = result.data['id'];
                    var parents = that.parents(".li-info");
                    var person = "/person/" + user.uuid + ".html", nick = user.nickname;
                    var li = '<li> <div class="zi-pl-content"> <a href="' + person + '" target="_blank" class="zi-nick">' + nick + '</a>： ' + content + ' </div> <div class="zi-cz" data-id="' + comm_id + '"> <a class="huifubtn">回复</a> · 刚刚 </div> </li>';
                    /*开始模拟将自己的回复写入网页*/
                    if (that.parents(".li-go").length > 0) {

                        if (parents.find(".zi-pl").length > 0) {
                            parents.find(".zi-pl ul").prepend(li);
                        } else {
                            parents.find(".li-content").after('<div class="zi-pl"><ul>' + li + '</ul></div>');
                        }

                    } else {
                        var clickNick = that.parents(".zi-cz").parent().find(".zi-pl-content .zi-nick").eq(0);
                        parents.find(".zi-pl ul").prepend('<li> <div class="zi-pl-content"><a href="' + person + '" target="_blank" class="zi-nick" style="margin-right:7px;">' + nick + '</a>回复   <a href="' + clickNick.attr("href") + '" target="_blank" class="zi-nick" style="margin-right:7px;">' + clickNick.html() + '</a> ： ' + content + ' </div> <div class="zi-cz" data-id="' + comm_id + '"> <a class="huifubtn">回复</a> · 刚刚 </div> </li>');
                    }

                }
                $(".huifu").parent().find(".huifubtn").html(atext);
                $(".huifu").remove();
                sendhf = true;
            }
        });
    } else {
        layer.msg("您好像还没有编写回复内容~");
    }
});

/*评论列表点赞*/
$("body").delegate(".li-dz", "click", function (e) {
    var that = $(this);
    if ($(this).hasClass("hover")) {
        layer.msg("您已经为Ta点赞啦！");
    } else {

        var id = that.parents('.li-info').data('id');
        request({
            url: config.api.thumbs_up,
            data: {id: id},
            loading: false,
            success: function (result) {
                if (result.code === 1) {
                    var numbers = parseInt(that.attr("data-dz")) + 1;
                    that.addClass("hover").attr("data-dz", numbers).html('<i class="iconfont icon-dianzan"></i>赞' + castnum(numbers));
                } else {
                    layer.msg("您已经赞过啦！");
                    that.addClass("hover")
                }
            }
        });
    }
});


// 回复评论
function reply(obj) {
    var boxTextarea = $(obj).parents(".zhiChi").eq(0).find(".b-box-textarea");
    if (boxTextarea.length == 1) {
        boxTextarea.remove();
    }else{
        var aid = $(obj).attr('aid');
        var pid = $(obj).attr('pid');
        var username = $(obj).attr('username');
        var floor = $(obj).parents('.reply').find(".gh").length;
        if(!comment_basecolor) comment_basecolor = '#39a7e4';
        floor = parseInt(floor)+1;
        var emoteHtml = '';
        if (showQQ=='1'){
            emoteHtml='<a class="ds-toolbar-button ds-add-emote hf" title="插入表情" ></a>';
        }
        var contact_input = '';
        if(is_login==0){
            contact_input +='<input class="b-email" type="text" name="email" placeholder="你的'+visitor_fill+'" value="">';
        }
        var emojiopne = '<script>$("textarea.hf").emoji({button:".ds-toolbar-button.hf",showTab:true,animation:"fade",basePath:config.api.emoji_dir,icons:emojiLists,});</script>';
        var str = '<div class="b-box-textarea"><div class="b-box-textarea-body"><textarea class="b-box-content hf" contenteditable="true" onfocus="delete_hint(this)"></textarea><ul class="b-emote-submit"><li class="b-emote">'+emoteHtml+contact_input+'<div class="b-tuzki"></div></li><li class="b-submit-button"><input type="button" value="评 论" aid="' + aid + '" pid="' + pid + '" username="' + username + '" floor="'+floor+'" class="sendhf"  style="background-color: '+comment_basecolor+';"></li><li class="b-clear-float"></li></ul></div><div class="error-tip"></div></div>'+emojiopne+'';

        var parentObj = $(obj).parents('.zhiChi').eq(0).append(str);
    }
}

// 删除提示和样式
function delete_hint(obj) {
    var word = $(obj).text();
    if (word == comment_tips) {
        $(obj).text('');
        $(obj).css('color', '#333');
    }
}
// 删除提示和样式
function addView(aid) {
    request({
        url: config.api.add_view+'?aid='+aid,
        async: false,
        loading: false,
        success: function (res) {
            if(res.code==1){
                var data=res.data;
                $('#viewNum').text(data.view);
                $('#commentNum').text(data.comment_num);
                $('#zan').text(data.praise_num);
            }
        }
    });
}

function get_ajax_comment(aid, start, limit,orderWay,type) {
    var url = PLUS_URL+"/comment_ajax.php";
    var param = {dopost:'getlist',aid: aid, start: start, limit: limit,orderWay:orderWay};

    $.getJSON(url, param, function (data) {
        $(".comment-load").hide();
        if(data.count) $(".comment-count").text(data.count);
        if (data.html) $(".empty-prompt-w").remove();
        if (type=='refresh'){
            $("#ulcommentlist").html(data.html);

        }else{
            $("#ulcommentlist").append(data.html);

        }
        $(".section-page-w").html(data.page);
        $(".section-emoji").html(data.emoji);
    });
}

//获取cookie
function getCookieValue(cookieName) {
    var cookieValue = document.cookie;
    var cookieStartAt = cookieValue.indexOf("" + cookieName + "=");
    if (cookieStartAt == -1) {
        cookieStartAt = cookieValue.indexOf(cookieName + "=");
    }
    if (cookieStartAt == -1) {
        cookieValue = null;
    }
    else {
        cookieStartAt = cookieValue.indexOf("=", cookieStartAt) + 1;
        cookieEndAt = cookieValue.indexOf(";", cookieStartAt);
        if (cookieEndAt == -1) {
            cookieEndAt = cookieValue.length;
        }
        cookieValue = unescape(cookieValue.substring(cookieStartAt, cookieEndAt));//解码latin-1
    }
    return cookieValue;
}


$(document).on('click', '.commentVote', function (event) {
    var ftype = $(this).data('type');
    var fid = $(this).data('id');
    var dz = $(this).data('dz');
    var taget_obj = $(this);
    var saveid = GetCookie('badgoodid');
    if(saveid != null)
    {
        var saveids = saveid.split(',');
        var hasid = false;
        saveid = '';
        j = 1;
        for(i=saveids.length-1;i>=0;i--)
        {
            if(saveids[i]==fid && hasid) continue;
            else {
                if(saveids[i]==fid && !hasid) hasid = true;
                saveid += (saveid=='' ? saveids[i] : ','+saveids[i]);
                j++;
                if(j==10 && hasid) break;
                if(j==9 && !hasid) break;
            }
        }
        if(hasid) { layer.msg('您刚才已表决过了喔！', function(){
        }); return false; }
        else saveid += ','+fid;
        SetCookie('badgoodid',saveid,1);
    }
    else
    {
        SetCookie('badgoodid',fid,1);
    }
    var tip = ftype=='support' ? '顶' :'踩';
    $.post(config.api.user_praise,{subject:'COMMENT',id:fid,type:ftype},function (data) {
        if (data.code==1){

            taget_obj.text(tip+'('+(dz+1)+')');
        }
    },'json');
});




//读写cookie函数
function GetCookie(c_name)
{
    if (document.cookie.length > 0)
    {
        c_start = document.cookie.indexOf(c_name + "=")
        if (c_start != -1)
        {
            c_start = c_start + c_name.length + 1;
            c_end   = document.cookie.indexOf(";",c_start);
            if (c_end == -1)
            {
                c_end = document.cookie.length;
            }
            return unescape(document.cookie.substring(c_start,c_end));
        }
    }
    return null
}

function SetCookie(c_name,value,expiredays)
{
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" +escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
}
function getHeadPic() {
    var url =PLUS_URL+'/comment_ajax.php';
    $.getJSON(url,{action:'getHeadPic'},function (data) {
        if (data.code==0){
            $(".qy-comment .b-head-img").attr('src',data.data);
            $(".qy-comment .b-email").hide();
        }
        if (data.is_login){
            is_login = 1;
            $(".qy-comment .b-email").hide();
        }
    });
}

/*初始化数据方法*/

function comments_data(data, isHot) {

    if (isHot) {
        data.list['comments'] = data.list['comments_hot']
    }
    var comments = data.list['comments'];
    var comments_reply = data.list['comments_reply'];
    //处理评论数据
    comments.forEach(function (value, i) {
        value.reply = [];
        comments_reply.forEach(function (item, j) {
            if (value.id === item['root_id']) {
                value.reply.push(item);
            }
        });
    });
    return comments;
}
